import base64
import hashlib
import hmac
import re
from Crypto.Cipher import DES3
from Crypto.Util.Padding import pad
from requests import post
from json import dumps,loads
from log import logger

def DoPayByPassWord(password:str, payUrl:str):
    paySecond = 0
    if TransPassWordCheck(password, payUrl):
        TransVerifyQuery(payUrl)
        while True:
            paySecond += 1
            if paySecond >= 5:
                return True
            if BalancePay(payUrl):
                return True

def TransPassWordCheck(password:str, payUrl:str):
    pattern = r"hfpwallet(.*?)pay"
    match = re.search(pattern, payUrl)
    if match:
        Mer_cust_id = match.group(1)

    pattern = r"uuid=(.*?)(&|$)"
    match = re.search(pattern, payUrl)
    if match:
        uuid = match.group(1)
    password = PassWordDES(password, uuid)
    signData = "password=" + password
    Check_value = CheckValueHmacSHA256(signData)

    url = "https://hfpay.cloudpnr.com/api/hfpwalleth5/transpasswordcheck"

    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
        "Content-Type": "application/json",
        "Check_value": Check_value,
        "Uuid": uuid,
        "Mer_cust_id": Mer_cust_id
    }

    data = {
        "password": password
    }

    data = dumps(data)
    resp = post(url=url, headers=headers, data=data)
    resp_json = loads(resp.text)
    if resp_json["resp_desc"] == "成功":
        logger.info("密码输入成功")
        return True
    else:
        logger.error("密码输入失败: {}".format(resp_json["resp_desc"]))
        return False

def TransVerifyQuery(payUrl:str):
    pattern = r"hfpwallet(.*?)pay"
    match = re.search(pattern, payUrl)
    if match:
        Mer_cust_id = match.group(1)

    pattern = r"uuid=(.*?)(&|$)"
    match = re.search(pattern, payUrl)
    if match:
        uuid = match.group(1)
    signData = 'dev_info_json={"devType":"2","devSysType":"H5","mobileFlag":"Y"}&trans_type=30'
    Check_value = CheckValueHmacSHA256(signData)

    url = "https://hfpay.cloudpnr.com/api/hfpwalleth5/transverifyquery"

    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
        "Content-Type": "application/json",
        "Check_value": Check_value,
        "Uuid": uuid,
        "Mer_cust_id": Mer_cust_id
    }

    data = {
        "trans_type": "30",
        "dev_info_json": "{\"devType\":\"2\",\"devSysType\":\"H5\",\"mobileFlag\":\"Y\"}"
    }

    data = dumps(data)
    resp = post(url=url, headers=headers, data=data)
    resp_json = loads(resp.text)
    if resp_json["resp_desc"] == "成功":
        logger.info("自动支付校验成功")
        return True
    else:
        logger.error("自动支付校验失败: {}".format(resp_json["resp_desc"]))
        return False

def BalancePay(payUrl:str):
    pattern = r"hfpwallet(.*?)pay"
    match = re.search(pattern, payUrl)
    if match:
        Mer_cust_id = match.group(1)

    pattern = r"uuid=(.*?)(&|$)"
    match = re.search(pattern, payUrl)
    if match:
        uuid = match.group(1)
    signData = 'dev_info_json={"devType":"2","devSysType":"H5","mobileFlag":"Y"}'
    Check_value = CheckValueHmacSHA256(signData)

    url = "https://hfpay.cloudpnr.com/api/hfpwalleth5/balancepay"

    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
        "Content-Type": "application/json",
        "Check_value": Check_value,
        "Uuid": uuid,
        "Mer_cust_id": Mer_cust_id
    }

    data = {
        "dev_info_json": "{\"devType\":\"2\",\"devSysType\":\"H5\",\"mobileFlag\":\"Y\"}"
    }

    data = dumps(data)
    try:
        resp = post(url=url, headers=headers, data=data)
        resp_json = loads(resp.text)
        if resp_json["resp_desc"] == "成功":
            logger.info("自动支付成功")
            return True
        else:
            logger.error("自动支付失败: {}".format(resp_json["resp_desc"]))
            return True
    except Exception as e:
        logger.error("自动支付失败: {}".format(e))
        return False

def PassWordDES(password:str, uuid:str, n="chinapnr"):
    mode = DES3.MODE_CBC
    key = uuid.encode('utf-8')
    key = key[:24]
    cipher = DES3.new(key, mode=mode)
    iv = n.encode('utf-8')
    cipher = DES3.new(key, mode=mode, iv=iv)
    encrypted = cipher.encrypt(pad(password.encode('utf-8'), cipher.block_size))
    ciphertext = base64.b64encode(encrypted).decode('utf-8')
    return ciphertext

def CheckValueHmacSHA256(data:str, key="chinapnr"):
    hmacHash = hmac.new(key.encode(), data.encode(), hashlib.sha256).digest()
    return hmacHash.hex()
